using System;
using System.Windows.Forms;
using RollManager.Library;

namespace RollManager.Forms.MainPanels
{
    public partial class UserConfigPanel : UserControl, MainPanel
    {
        private int oldIndex = -1;

        private ConfigSetting ConfigSetting
        {
            get
            {
                return (ConfigSetting) settingsList.SelectedItem;
            }
        }

        public UserConfigPanel()
        {
            InitializeComponent();
        }

        public override void Refresh()
        {
            base.Refresh();

            settingsList.DataSource = Database.GetConfigSettings();
            settingsList.DisplayMember = ItemBase.NAME_PROPERTY;
            settingsList.SelectedIndex = -1;
        }

        private void settingsList_SelectionChangeCommitted( object sender, EventArgs e )
        {
            if( oldIndex != -1 )
            {
                Database.SaveUserSetting( ( (ConfigSetting) settingsList.Items[ oldIndex ] ).Id, settingBox.Text );
            }

            if( settingsList.SelectedIndex != -1 )
            {
                oldIndex = settingsList.SelectedIndex;
                descriptionBox.Text = ConfigSetting.Description;
                settingBox.Text = Database.GetUserSetting( ConfigSetting.Id );
            }
        }

        #region MainPanel Members

        public void Save()
        {
            settingsList_SelectionChangeCommitted( null, null );
        }

        #endregion
    }
}